package com.example.gateway.filter;

/**
 * @author FanFu
 * @version 1.0
 * @date 2025/11/8 20:29
 */
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");

        log.info("网关请求路径: {}, Token: {}", path, token);

        // 跳过登录接口的认证（如果有的话）
        if (path.contains("/user/login")) {
            return chain.filter(exchange);
        }

        // 简单的token验证（实际项目需要更复杂的认证逻辑）
        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("未授权的访问: {}", path);
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
